package com.deductive.netty.websocket.service;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class NettyConnectionManager {

    private static final Logger logger = LoggerFactory.getLogger(NettyConnectionManager.class);

    private static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static final ConcurrentMap<String, ChannelId> userChannelMap = new ConcurrentHashMap<>();
    private static final ConcurrentMap<ChannelId, String> channelUserMap = new ConcurrentHashMap<>();

    public static void addChannel(String userId, Channel channel) {
        channels.add(channel);
        userChannelMap.put(userId, channel.id());
        channelUserMap.put(channel.id(), userId);
        logger.info("用户 {} 通过通道 {} 连接成功", userId, channel.id());
    }

    public static void removeChannel(Channel channel) {
        channels.remove(channel);
        String userId = channelUserMap.remove(channel.id());
        if (userId != null) {
            userChannelMap.remove(userId);
            logger.info("用户 {} 断开连接，通道 {} 已移除", userId, channel.id());
        }
    }

    public static Channel getChannel(String userId) {
        ChannelId channelId = userChannelMap.get(userId);
        if (channelId == null) {
            return null;
        }
        return channels.find(channelId);
    }

    public static String getUserId(Channel channel) {
        return channelUserMap.get(channel.id());
    }

    public static ChannelGroup getChannels() {
        return channels;
    }

    /**
     * 获取所有在线用户的ID列表
     *
     * @return 在线用户的ID集合
     */
    public static java.util.Set<String> getOnlineUsers() {
        return userChannelMap.keySet();
    }
}